<template>
  <div id="userLoginPage">
    <h2 class="title">智慧云图库 - 用户登录</h2>
    <div class="desc">企业级智慧协同云图库</div>
    <!-- autocomplete="on" 浏览器是否要自动输入历史记录中的密码
         -->
    <a-form
      :model="formState"
      autocomplete="on"
      @finish="handleSubmit"
      @finishFailed="onFinishFailed"
    >
      <a-form-item name="userAccount" :rules="[{ required: true, message: '请输入账号' }]">
        <a-input v-model:value="formState.userAccount" placeholder="请输入账号" />
      </a-form-item>

      <a-form-item
        name="userPassword"
        :rules="[
          { required: true, message: '请输入用户密码' },
          { min: 8, message: '密码长度不能小于8' },
        ]"
      >
        <a-input-password v-model:value="formState.userPassword" placeholder="请输入密码" />
      </a-form-item>
      <div class="tips">没有账号？ <RouterLink to="/user/register">立即注册</RouterLink></div>

      <a-form-item>
        <a-button type="primary" html-type="submit" style="width: 100%">登录</a-button>
      </a-form-item>
    </a-form>
  </div>
</template>
<script lang="ts" setup>
import { onMounted, reactive } from 'vue'
import { userLoginUsingPost } from '@/api/userController.ts'
import { useLoginUserStore } from '@/stores/useLoginUserStore.ts'
import { message } from 'ant-design-vue'
import router from '@/router'
//用于接受表单输入的值
const formState = reactive<API.UserLoginRequest>({
  userAccount: '',
  userPassword: '',
})
const loginUserStore = useLoginUserStore();

/**
 * 默认接受当前表单的值
 * @param values
 */
const handleSubmit = async (values: any) => {
  const res = await userLoginUsingPost(values)
  //自定义状态码为0，表示登录成功；data存在，表示有信息
  //登录成功后，应该将登录态保存到全局状态中，方便其他页面使用
  if (res.data.code === 0 && res.data.data){
    //这里是从后端获取用户信息，并保存到全局状态中
    //也可以注解将表单穿过来的用户信息保存到全局状态中
    await loginUserStore.fetchLoginUser();
    message.success("登录成功");
    router.replace({
      path: '/',//跳转会true
      replace: true,//跳转后，让新页面覆盖（代替）掉当前的页面，防止用户返回登录页面
    })
    // const currentUrl = window.location.href;
    // const urlParams = new URLSearchParams(new URL(currentUrl).search);
    // const redirectUrl = urlParams.get('redirect');
    //
    // if (redirectUrl) {
    //   console.log("重定向地址：", redirectUrl)
    //   window.location.href = redirectUrl;
    // } else {
    //   router.push('/'); // 默认跳转到主页
    // }
  }else {
    message.error("登录失败" + res.data.message);
  }
}

const onFinishFailed = (errorInfo: any) => {
  console.log("登录失败")
  console.log('Failed:', errorInfo)
}


</script>

<style scoped>
#userLoginPage {
  width: 360px;
  margin: 0 auto;
}

.title {
  text-align: center;
  margin-bottom: 16px;
}

.desc {
  color: #666;
  text-align: center;
  margin-bottom: 16px;
}

.tips {
  color: #666;
  text-align: right;
  font-size: 13px;
}
</style>
